package bjtu.tjj.simpledy.service.impl;

import bjtu.tjj.simpledy.common.ResultCode;
import bjtu.tjj.simpledy.exception.CommonException;
import bjtu.tjj.simpledy.mapper.VideoMapper;
import bjtu.tjj.simpledy.mapper.WatchMapper;
import bjtu.tjj.simpledy.service.WatchService;
import bjtu.tjj.simpledy.utils.ThreadLocalUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class WatchServiceImpl implements WatchService {
    private final WatchMapper watchMapper;
    private final VideoMapper videoMapper;

    @Override
    public void onWatch(Long videoId) {
        if (!videoMapper.exists(videoId)) {
            throw new CommonException(ResultCode.VIDEO_NOT_EXIST);
        }
        long userId = ThreadLocalUtils.getUserId();
        int res = watchMapper.insert(userId, videoId);
        if (res > 0) {
            return;
        }
        res = watchMapper.increment(userId, videoId);
        if (res == 0) {
            throw new CommonException();
        }
    }
}
